#!/bin/bash

# JSON配置文件的路径
CONFIG_FILE="copy_config.json"

# 检查JSON配置文件是否存在
if [ ! -f "$CONFIG_FILE" ]; then
  echo "Configuration file does not exist."
  exit 1
fi

# 使用 jq 解析 JSON 文件
# 此处假设 jq 已正确安装
while IFS= read -r line; do
  # 分割键和值
  IFS=' ' read -ra ADDR <<< "$line"
  SOURCE_PATH="${ADDR[0]}"
  TARGET_PATH="${ADDR[1]}"
  
  # 确保源路径存在
  if [ ! -e "$SOURCE_PATH" ]; then
    echo "Source path $SOURCE_PATH does not exist."
    continue
  fi
  
  # 创建目标目录的父目录，以确保目标路径存在
  mkdir -p "$(dirname "$TARGET_PATH")"
  
  # 如果源路径是目录，直接拷贝整个目录
  if [ -d "$SOURCE_PATH" ]; then
    echo "Copying directory $SOURCE_PATH to $TARGET_PATH"
    cp -R "$SOURCE_PATH" "$TARGET_PATH"
  else
    # 单个文件拷贝
    echo "Copying $SOURCE_PATH to $TARGET_PATH"
    cp "$SOURCE_PATH" "$TARGET_PATH"
  fi
done < <(jq -r 'to_entries | .[] | "\(.key) \(.value)"' "$CONFIG_FILE")

echo "Copy operation completed."
